package system

import (
	"context"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type DeviceApi struct{}

// CreateDevice 创建设备表
// @Tags Device
// @Summary 创建设备表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.Device true "创建设备表"
// @Success 200 {object} response.Response{msg=string} "创建成功"
// @Router /device/createDevice [post]
func (deviceApi *DeviceApi) CreateDevice(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	var device system.Device
	err := c.ShouldBindJSON(&device)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = deviceService.CreateDevice(ctx, &device)
	if err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("创建成功", c)
}

// DeleteDevice 删除设备表
// @Tags Device
// @Summary 删除设备表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.Device true "删除设备表"
// @Success 200 {object} response.Response{msg=string} "删除成功"
// @Router /device/deleteDevice [delete]
func (deviceApi *DeviceApi) DeleteDevice(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	ID := c.Query("ID")
	err := deviceService.DeleteDevice(ctx, ID)
	if err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("删除成功", c)
}

// DeleteDeviceByIds 批量删除设备表
// @Tags Device
// @Summary 批量删除设备表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{msg=string} "批量删除成功"
// @Router /device/deleteDeviceByIds [delete]
func (deviceApi *DeviceApi) DeleteDeviceByIds(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	IDs := c.QueryArray("IDs[]")
	err := deviceService.DeleteDeviceByIds(ctx, IDs)
	if err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("批量删除成功", c)
}

// UpdateDevice 更新设备表
// @Tags Device
// @Summary 更新设备表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data body system.Device true "更新设备表"
// @Success 200 {object} response.Response{msg=string} "更新成功"
// @Router /device/updateDevice [put]
func (deviceApi *DeviceApi) UpdateDevice(c *gin.Context) {
	// 从ctx获取标准context进行业务行为
	ctx := c.Request.Context()

	var device system.Device
	err := c.ShouldBindJSON(&device)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = deviceService.UpdateDevice(ctx, device)
	if err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败:"+err.Error(), c)
		return
	}
	response.OkWithMessage("更新成功", c)
}

// FindDevice 用id查询设备表
// @Tags Device
// @Summary 用id查询设备表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param ID query uint true "用id查询设备表"
// @Success 200 {object} response.Response{data=system.Device,msg=string} "查询成功"
// @Router /device/findDevice [get]
func (deviceApi *DeviceApi) FindDevice(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	ID := c.Query("ID")
	redevice, err := deviceService.GetDevice(ctx, ID)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败:"+err.Error(), c)
		return
	}
	response.OkWithData(redevice, c)
}

// GetDeviceList 分页获取设备表列表
// @Tags Device
// @Summary 分页获取设备表列表
// @Security ApiKeyAuth
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.DeviceSearch true "分页获取设备表列表"
// @Success 200 {object} response.Response{data=response.PageResult,msg=string} "获取成功"
// @Router /device/getDeviceList [get]
func (deviceApi *DeviceApi) GetDeviceList(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	var pageInfo systemReq.DeviceSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := deviceService.GetDeviceInfoList(ctx, pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败:"+err.Error(), c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}

// GetDevicePublic 不需要鉴权的设备表接口
// @Tags Device
// @Summary 不需要鉴权的设备表接口
// @Accept application/json
// @Produce application/json
// @Success 200 {object} response.Response{data=object,msg=string} "获取成功"
// @Router /device/getDevicePublic [get]
func (deviceApi *DeviceApi) GetDevicePublic(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	// 此接口不需要鉴权
	// 示例为返回了一个固定的消息接口，一般本接口用于C端服务，需要自己实现业务逻辑
	deviceService.GetDevicePublic(ctx)
	response.OkWithDetailed(gin.H{
		"info": "不需要鉴权的设备表接口信息",
	}, "获取成功", c)
}

// 填充funcName
// @Tags Device
// @Summary 查询设备信息
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.DeviceSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /device/search [GET]
func (deviceApi *DeviceApi) SearchDevice(c *gin.Context) {
	// 1. 解析参数（改用 ShouldBindQuery 增强校验）
	var deviceSearch systemReq.DeviceSearch
	if err := c.ShouldBindQuery(&deviceSearch); err != nil {
		global.GVA_LOG.Error("参数解析失败: " + err.Error())
		response.FailWithMessage("参数错误: "+err.Error(), c)
		return
	}

	// 2. 补充默认分页参数（防止 Service 层重复处理）
	if deviceSearch.Page <= 0 {
		deviceSearch.Page = 1
	}
	if deviceSearch.PageSize <= 0 {
		deviceSearch.PageSize = 10
	}

	// 3. 调用 Service 层
	devices, total, err := deviceService.SearchDevice(context.Background(), deviceSearch)
	if err != nil {
		global.GVA_LOG.Error("设备查询失败: " + err.Error())
		response.FailWithMessage("查询失败: "+err.Error(), c)
		return
	}

	// 4. 构造标准响应（与前端约定格式）
	response.OkWithData(map[string]interface{}{
		"list":  devices,
		"total": total,
	}, c)
}

// Running 运行监测
// @Tags Device
// @Summary 运行监测
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.DeviceSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /device/running [GET]
func (deviceApi *DeviceApi) Running(c *gin.Context) {
	// 创建业务用Context
	ctx := c.Request.Context()

	// 调用服务层获取统计数据
	counts, err := deviceService.Running(ctx)
	if err != nil {
		global.GVA_LOG.Error("获取设备统计失败!", zap.Error(err))
		response.FailWithMessage("获取设备统计失败:"+err.Error(), c)
		return
	}

	response.Count(counts, c)
}

// Realtime 实时监测数据
// @Tags Device
// @Summary 实时监测数据
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.DeviceSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /device/realtime [GET]
func (deviceApi *DeviceApi) Realtime(c *gin.Context) {
	ctx := c.Request.Context()
	// 明确接收 []DeviceResp 类型
	data, err := deviceService.Realtime(ctx)
	if err != nil {
		global.GVA_LOG.Error("实时数据接口异常", zap.Error(err))
		response.FailWithDetailed(err.Error(), "获取实时设备数据失败", c)
		return
	}

	response.OkWithData(data, c)
}

// Address 可以根据设备状态和设备地址在地图上展示所有设备的所在地，以及所有设备的状态
// @Tags Device
// @Summary 可以根据设备状态和设备地址在地图上展示所有设备的所在地，以及所有设备的状态
// @Accept application/json
// @Produce application/json
// @Param data query systemReq.DeviceSearch true "成功"
// @Success 200 {object} response.Response{data=object,msg=string} "成功"
// @Router /device/address [GET]
func (deviceApi *DeviceApi) Address(c *gin.Context) {
	ctx := c.Request.Context()
	statData, err := deviceService.Address(ctx)
	if err != nil {
		global.GVA_LOG.Error("查询设备地址统计数据失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}

	response.OkWithData(statData, c)
}
